package com.export.thread;

import com.alibaba.fastjson.JSONObject;
import com.export.bean.model.ExportModel;
import com.export.bean.model.StateModel;
import com.export.config.Contansts;
import com.export.service.Impl.DeviceKvHistoryRepository_UNITED;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;

/**
 * Created by Studio on 2017/5/11.
 * 优耐特斯
 * 读取redis队列线程
 */
@Component
public class PopThread_UNITED extends Thread{

    private static final Logger logger = LoggerFactory.getLogger(ActionThread.class);


    @Autowired
    DeviceKvHistoryRepository_UNITED deviceKvHistoryRepositoryUNITED;
    @Autowired
    private JedisPool jedisPool;

    private static PopThread_UNITED popThreadUNITED;
    private StateModel stateModel;

    private Jedis redis ;//= new Jedis(Contansts.redisHost, 6379,100000);

    public PopThread_UNITED() {
        stateModel = new StateModel();
    }

    @PostConstruct     //关键二   通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
    public void init() {
        popThreadUNITED = this;
        popThreadUNITED.deviceKvHistoryRepositoryUNITED = this.deviceKvHistoryRepositoryUNITED;
        popThreadUNITED.jedisPool = this.jedisPool;
    }

    @Override
    public void run() {
        redis = popThreadUNITED.jedisPool.getResource();
        logger.info("/*********Open reading "+Contansts.listName_united+"/开启读取队列线程(优耐特斯)****************/");

        while(true){
            if(stateModel.getPopState() == 0){
                stateModel.setPopState(1);
                String result = redis.rpop(Contansts.listName_united);
                if(result != null){
                    logger.info("get an exporting message/得到一条导出信息(优耐特斯)");
                    logger.info(result);
                    ExportModel exportModel = getModel(result);
                    MultiExportThread_UNITED multiExportThreadUNITED = new MultiExportThread_UNITED(stateModel,exportModel,
                            popThreadUNITED.deviceKvHistoryRepositoryUNITED,redis);
                    multiExportThreadUNITED.start();
                }else{
                    stateModel.setPopState(0);
                }
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static ExportModel getModel(String jsonStr){

        ExportModel exportModel = JSONObject.toJavaObject(JSONObject.parseObject(jsonStr), ExportModel.class);
        return exportModel;
    }
}
